#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Mikan MongoDB KVS Key Value Store 機能

Mikan Python Web Framework
"""

__author__ = "K.Sonohara"
__status__ = "develop"
__version__ = "0.0.0_23"
__date__    = "2013/07/07"
__license__ = 'LGPL'

# ------------------------------------------------------------
## インポート
# ------------------------------------------------------------
# Python
import datetime, traceback


# Mongo
import pymongo

# ESiPC
from esipc import ESiPCProperty

# Mikan
from mikan.kvs import AbstractMikanKVS
from mikan.exception import MikanExceptions
from mikan.exception.item import  MikanLockItemException, MikanUnlockItemException

# ------------------------------------------------------------
## 変数
# ------------------------------------------------------------

# ------------------------------------------------------------
## 関数
# ------------------------------------------------------------

# ------------------------------------------------------------
## クラス
# ------------------------------------------------------------
class MIKAN_MONGODBKVS(object):
	pass

# ------------------------------------------------------------
## Mikan SQLite KVS クラス
#
class MikanMongoDBKVS(AbstractMikanKVS, MIKAN_MONGODBKVS):

	def get_kvs_version(self):
		return pymongo.version

	def get_kvs_name(self):
		return u"MongoDB"

	def __init__(self, request):
		super(MikanMongoDBKVS, self).__init__( request)

		self.FDatabase = None

	def get_database(self):
		return self.FDatabase

	def setup(self, config, section):
		host = "localhost"
		try:
			host = str(config.get(section, "url"))
		except:
			pass

		self.connect(config.get(section, "database"), host)

	def connect(self, database, host="localhost"):
		self.connector = pymongo.MongoClient(host)
		self.FDatabase = self.connector[database]

	def get_collection(self, name):
		return self.database[name]

	def get(self, table, key, name):
		c = self.get_collection(table)

		v = None
		try:
			v = c.find_one({"key": key})
		except:
			pass

		if v == None:
			return None

		try:
			return v[name]
		except:
			return None

	def set(self, table, key, name, value):
		c = self.get_collection(table)
		v = None
		try:
			v = c.find_one({"key": key})
		except:
			pass
		if v == None:
			v = {"key": key}
		v[name] = value
		c.save(v)

	# ----------------------------------------------------
	## Property
	database = ESiPCProperty(get_database, None, None)

# ------------------------------------------------------------
## メイン関数
# ------------------------------------------------------------
if __name__ == '__main__':
	pass

# ------------------------------------------------------------
